﻿using Common;
using CommunityToolkit.Mvvm.ComponentModel;
using EV.EventBus;
using NPOI.SS.Formula;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Security.AccessControl;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using ZoneLine.Models;
using ZoneLine.PlcMaster;
using ZoneLine.Stations.HStation;

namespace ZoneLine.Stations
{
    /// <summary>
    /// 后减OP620
    /// </summary>
    /// <remarks>
    /// <para>衬套压装工位</para>
    /// <para>StationCode：OP620    IP：192.168.10.10</para>
    /// </remarks>
    public class HOP010Station : HStationBase
    {
        public HOP010Station()
        {
            _logUiChannel = nameof(HOP010Station) + "uilog";
        }

        public void Init(string ip, int port = 102, string startAddr = "DB1000.0", string endUploadCodeAddr = "DB1001.8", string endUploadDataAddr = "DB1001.2", string allowWorkAddr = "DB1001.8")
        {
            Ip = ip;
            Port = port;
            _startAddr = startAddr;
            _readLength = 1028;
            StationCode = "OP620";
            EndUpLoadCodeAddr = endUploadCodeAddr;
            EndUpLoadDataAddr = endUploadDataAddr;
            AllowWorkAddr = allowWorkAddr;
            HeartToPlcAddr = "DB1001.0";
            StationRecordData = new HOP010StationResult();
            WorkDirectionAddr = "DB1001.14";
            CurrentProductTypeAddr = "DB1001.2168";
            CurrentProductModelAddr = "DB50.8";
            FormulaNameAddr = "DB50.0";
            FormulaAddr = "DB1001.32";

            //TaskMaster.Default.AddCycleTask(nameof(HOP010Station), 1, () =>
            //{
            //    ////var value = (short)Cache.WorkDirection;
            //    ////WriteData(WorkDirectionAddr, value);
            //    ////_client?.Write(CurrentProductTypeAddr, Cache.CurrentProductType);

            //    //WriteData(CurrentProductTypeAddr, Cache.CurrentProductType);
            //    //WriteData(CurrentProductModelAddr, Cache.WorkDirection == Common.WorkDirectionEnum.Left ? "L" : "R");
            //    //WriteData(FormulaNameAddr, Cache.CurrentProductType);

            //    //var formula = Cache.CurrentFormula.Where(o => o.IP == ip).FirstOrDefault().FormulaNumber;
            //    //var rlt = WriteData(FormulaAddr, (short)formula);
            //    //LogWithUi(_logUiChannel, $"在{CurrentStationName}工位向下位机下发消息，下发配方{formula},rlt={rlt}", StationRecordData.AbsScanCode);

            //}, false, EV.EventBus.CycleTask.TimeBaseEnum._1S);

            //MessageCenter.Subscribe("App_Exit_Event", "App_Exit_Event", (arg) =>
            //{
            //    var res = WriteData(FormulaAddr, (short)0);
            //    return Task.CompletedTask;
            //});

            base.InitReSetAddr();
        }

        protected override async void DealWithSignal(string name)
        {
            if (name == nameof(StartUploadCode))
            {
                //todo 上传了条码 这时候验证是否要工作
                if (StartUploadCode)
                {
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}收到上传条码信息命令", StationRecordData.AbsScanCode);

                    #region 检查来料是否合格
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}检查来料是否合格", StationRecordData.AbsScanCode);
                    var mesRes = await ApiHelper.CheckIncomingMaterialIsOKAsync(StationRecordData.AbsScanCode);
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}{mesRes.errorMsg}", StationRecordData.AbsScanCode);
                    if (!mesRes.IsOk)
                    {
                        LogWithUi(_logUiChannel, $"在{CurrentStationName}{mesRes.errorMsg}", StationRecordData.AbsScanCode);
                        var writeRlt0 = WriteWorkActionToPlc(AllowWorkAddr, WorkActionEnum.CalHErr, StationRecordData.AbsScanCode);
                        LogWithUi(_logUiChannel, $"在{CurrentStationName}工位向下位机下发消息，下发{writeRlt0}", StationRecordData.AbsScanCode);
                        return;
                    }
                    #endregion

                    LogWithUi(_logUiChannel, $"在{CurrentStationName}工位结论验证,条码信息是{StationRecordData.AbsScanCode}", StationRecordData.AbsScanCode);
                    var validataRlt = Validata(CurrentStationName, StationRecordData.AbsScanCode);
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}工位的验证结果是{validataRlt}", StationRecordData.AbsScanCode);
                    var writeRlt = WriteWorkActionToPlc(AllowWorkAddr, validataRlt, StationRecordData.AbsScanCode);
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}工位向下位机下发消息，下发{writeRlt}", StationRecordData.AbsScanCode);
                    return;
                }
                else
                {
                    //LogWithUi(_logUiChannel, $"在{CurrentStationName}收到上传条码命令变为false", StationRecordData.AbsScanCode);
                    //WriteData(EndUpLoadCodeAddr, false);
                    //WriteData(AllowWorkAddr, 0, StationRecordData.AbsScanCode);

                    LogWithUi(_logUiChannel, $"在{CurrentStationName}收到上传条码命令变为false", StationRecordData.AbsScanCode);
                    WriteData(EndUpLoadCodeAddr, 0, StationRecordData.AbsScanCode);
                    WriteData(AllowWorkAddr, 0, StationRecordData.AbsScanCode);
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}复位工作控制指令和复位上传条码完成指令", StationRecordData.AbsScanCode);
                    return;
                }
            }

            if (name == nameof(StartUploadData))
            {
                if (StartUploadData)
                {
                    //todo 上传数据 这时候将数据记录到数据库中
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}收到上传记录数据命令", StationRecordData.AbsScanCode);

                    var rlt = RecordData();
                    WriteData(EndUpLoadDataAddr, (short)rlt, StationRecordData.AbsScanCode);
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}数据记录,rlt={rlt}", StationRecordData.AbsScanCode);
                }
                else
                {
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}收到上传记录数据命令变为false", StationRecordData.AbsScanCode);

                    WriteData(EndUpLoadDataAddr, (short)0, StationRecordData.AbsScanCode);
                    LogWithUi(_logUiChannel, $"在{CurrentStationName}数据记录,clear", StationRecordData.AbsScanCode);
                }
            }
        }

        protected override int RecordData()
        {
            var result = new HOP010StationResult()
            {
                AbsScanCode = StationRecordData.AbsScanCode,
                BushScanCode = StationRecordData.BushScanCode,
                StationCode = this.StationCode,
                PartType = StationRecordData.PartType,
                Result = StationRecordData.Result,
                PressPosition = StationRecordData.PressPosition,
                PressForce = StationRecordData.PressForce,
                CycleTime = StationRecordData.CycleTime,
            };
            var writeRlt = false;
            if (_dal.CheckExist<HOP010StationResult>(p => p.AbsScanCode == result.AbsScanCode))
            {
                var beforeRlt = _dal.GetModel<HOP010StationResult>(p => p.AbsScanCode == result.AbsScanCode);
                result.Id = beforeRlt.Id;
                writeRlt = _dal.UpdateModelSuper<HOP010StationResult>(p => p.AbsScanCode == result.AbsScanCode, result);
            }
            else
            {
                writeRlt = _dal.AddModel(result);
            }
            return writeRlt ? 1 : 2;
        }
    }
}